package com.willren.http;

import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class HttpRequestEx {

	public interface HttpRequestExInterface {
		public void httpDataReceived(int code, String response);
	}

	public enum HttpType {
		HT_GET, HT_POST
	}

	private HttpUriRequest request = null;

	public HttpRequestEx(HttpType type, String url,
			List<NameValuePair> header, List<NameValuePair> parameter) {

		switch (type) {
		case HT_GET:
			if (null != parameter && parameter.size() > 0) {
				StringBuffer sb = new StringBuffer(url);
				if (null != sb) {
					for (int index = 0; index < parameter.size(); index++) {
						if (0 == index) {
							sb.append('?');
						} else {
							sb.append('&');
						}
						sb.append(parameter.get(index).getName());
						sb.append("=");
						sb.append(parameter.get(index).getValue());
					}

					url = sb.toString();
				}
			}

			HttpGet get = new HttpGet(url);
			if (null != get) {
				request = get;
			}

			break;
		case HT_POST:
			HttpPost post = new HttpPost(url);
			if (null != post) {
				try {
					post.setEntity(new UrlEncodedFormEntity(parameter,
							HTTP.UTF_8));

					request = post;
				} catch (Exception e) {
				}
			}

			break;
		}
		
		if (null != request && null != header) {
			Header [] headers = new Header[header.size()];
			
			for (int index = 0; index < header.size(); index++) {
				headers[index] = new BasicHeader(header.get(index).getName(), header.get(index).getValue());
			}
			
			request.setHeaders(headers);
		}
	}

	public boolean send(HttpRequestExInterface callback) {

		boolean ret = false;
		final HttpRequestExInterface finalCallback = callback;

		if (null != request) {
			ret = true;

			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						HttpResponse httpResponse = new DefaultHttpClient()
								.execute(request);
						if (null != httpResponse) {
							int code = httpResponse.getStatusLine()
									.getStatusCode();
							String response = EntityUtils.toString(httpResponse
									.getEntity());

							if (null != finalCallback) {
								finalCallback.httpDataReceived(code, response);
							}
						}
					} catch (Exception e) {
					}
				}
			}).start();
		}

		return ret;
	}
}
